package com.bidepan.big_event.controller;

import ch.qos.logback.core.util.StringUtil;
import com.bidepan.big_event.pojo.Result;
import com.bidepan.big_event.pojo.User;
import com.bidepan.big_event.service.UserService;
import com.bidepan.big_event.utils.JwtUtil;
import com.bidepan.big_event.utils.Md5Util;
import com.bidepan.big_event.utils.ThreadLocalUtil;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Validated//数据校验
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;
//    注册
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^.{2,10}$") String username, @Pattern(regexp = "^.{5,16}$") String password) {
        //检查用户名是否存在
        User user = userService.findByUserName(username);
        if(user==null){
            //注册用户
            userService.add(username,password);
            return Result.success();
        }
        else{
            return Result.error("该用户名被占用");
        }
    }

    //登录
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^.{2,10}$") String username, @Pattern(regexp = "^.{5,16}$") String password){
        //根据用户名查询用户
        User loginUser = userService.findByUserName(username);
        //判断用户是否存在
        if(loginUser==null){
            return Result.error("用户名错误");
        }
        //判断密码是否正确
        if(Md5Util.getMD5String(password).equals(loginUser.getPassword())){
            //登录成功
            //下发令牌
            Map<String,Object> claims = new HashMap<String,Object>();   //荷载
            claims.put("id",loginUser.getId());
            claims.put("username",loginUser.getUsername());
            String token = JwtUtil.genToken(claims);     //令牌

            //把token存储到redis中（必须先开启redis服务器）
            redisTemplate.opsForValue().set(token,token,12, TimeUnit.HOURS);  //12小时过期

            return Result.success(token);
        }
        return Result.error("密码错误");
    }


    //得到用户信息
    @GetMapping("/userInfo")
    public Result<User> userInfo(/*   @RequestHeader(name="Authorization") String token    */){
        //根据用户名查询用户信息
        //从令牌中获取数据
//        Map<String,Object> map = JwtUtil.parseToken(token);    //获取令牌载荷

        //token获取数据改进为从全局ThreadLocal中获取数据
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }


    //更新用户信息(nickname,email,updateTime等)
    @PutMapping("/update")
    public Result update(@RequestBody @Valid User user){
        userService.update(user);
        return Result.success();
    }

    //更新用户头像
    @PatchMapping("updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    //修改密码
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String>params,@RequestHeader(name="Authorization") String token){
        //1.手动校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("请补全原密码，新密码，和确认密码");
        }
        //原密码是否正确
        //调用userService根据用户名拿到原密码，再和oldPwd比对
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        if(!user.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("原密码不正确");
        }
        //newPwd和rePwd是否一致
        if(!newPwd.equals(rePwd)){
            return Result.error("两次新密码不一致");
        }

        //2.调用service完成密码更新
        String newPwdMd5 = Md5Util.getMD5String(newPwd);
        userService.updatePassword(newPwdMd5);

        //删除redis中对应的token
        redisTemplate.opsForValue().
                getOperations().
                delete(token);

        return Result.success();
    }

}
